<!DOCTYPE html>
<html>
  <head>
    <title>
      OfflineAudioContext.startRendering Promise with oncomplete
    </title>
    <script src="../../resources/testharness.js"></script>
    <script src="../../resources/testharnessreport.js"></script>
    <script src="../resources/audit-util.js"></script>
    <script src="../resources/audit.js"></script>
  </head>
  <body>
    <script id="layout-test-code">
      let audit = Audit.createTaskRunner();

      let context;
      let promise;
      let renderedData;
      let promiseData;

      let sampleRate = 48000;
      let renderSeconds = 1;
      let renderFrames = sampleRate * renderSeconds;
      let contextChannels = 2;

      function compareData(should) {
        // The spec implies that the same buffer is returned by both oncomplete
        // and the promise. Check that they are identical.

        should(
            renderedData === promiseData,
            'AudioBuffer returned by oncomplete and promise are identical')
            .beTrue();
      }

      function checkResult(task, should, event) {
        renderedData = event.renderedBuffer;
        promise.then(function(result) {
          promiseData = result;
          compareData(should);
          task.done();
        });
      }

      // Create an offline context and verify that both the oncomplete and
      // promise are returned with the same stuff.
      audit.define(
          {
            label: 'test',
            description:
                'OfflineAudioContext.startRendering Promise with oncomplete'
          },
          (task, should) => {
            context = new OfflineAudioContext(
                contextChannels, renderFrames, sampleRate);

            let buffer =
                context.createBuffer(contextChannels, renderFrames, sampleRate);
            for (let k = 0; k < renderFrames; ++k) {
              buffer.getChannelData(0)[k] = 1;
              buffer.getChannelData(1)[k] = 2;
            }

            let source = context.createBufferSource();
            source.buffer = buffer;
            source.connect(context.destination);
            source.start();

            context.oncomplete = (event) => {
              checkResult(task, should, event);
            };

            promise = context.startRendering();

          });

      audit.run();
    </script>
  </body>
</html>
